package types

import (
	"github.com/tarm/serial"
	"sync"
)

// ConnSerialPool 所有连接对象
type ConnSerialPool struct {
	m sync.Map
}

func (c *ConnSerialPool) Load(commId string) (conn *SerialConn, ok bool) {
	var load any
	load, ok = c.m.Load(commId)

	if ok {
		conn = load.(*SerialConn)
	} else {
		conn = nil
	}

	return
}

func (c *ConnSerialPool) Store(commId string, conn *SerialConn) {
	c.m.Store(commId, conn)
}

func (c *ConnSerialPool) LoadOrStore(commId string, conn *SerialConn) (actual *SerialConn, loaded bool) {
	var store any
	store, loaded = c.m.LoadOrStore(commId, conn)

	if store != nil {
		actual = store.(*SerialConn)
	}

	return
}

func (c *ConnSerialPool) Delete(commId string) {
	c.m.Delete(commId)
}

func (c *ConnSerialPool) Range(f func(commId string, slave *SerialConn) bool) {
	f1 := func(key, value interface{}) bool {
		return f(key.(string), value.(*SerialConn))
	}
	c.m.Range(f1)
}

// SerialConn 从机
type SerialConn struct {
	Baud       int
	CommId     string
	SerialPort *serial.Port
}
